package com.atguigu.gmall.realtime.app.dwd.db;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.func.BaseDbTableProcessFunction;
import com.atguigu.gmall.realtime.beans.BaseDbTableProcess;
import com.atguigu.gmall.realtime.utils.KafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;

/**
 * @author Felix
 * @date 2023/8/4
 * 处理逻辑比较简单的事实表动态分流
 * 需要启动的进程
 *      zk、kafka、maxwell、BaseDbApp
 * DWD总结
 *      流量域
 *          错误日志事实表
 *          启动日志事实表
 *          曝光日志事实表
 *          动作日志事实表
 *          页面日志事实表
 *      交易域
 *          加购事实表
 *          下单事实表
 *          取消订单事实表
 *          支付成功事实表
 *          退单事实表
 *          退款成功事实表
 *      工具域
 *          优惠券领取事实表
 *          优惠券使用事实表
 *      互动域
 *          评论事实表
 *          收藏事实表
 *      用户域
 *          用户注册
 * dwd涉及的知识点
 *      状态编程
 *      侧输出流
 *      FlinkSQL相关知识
 *      动态分流处理
 */
public class BaseDbApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        /*
        //TODO 2.检查点相关的设置
        //2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 设置job取消后检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
        //2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        //2.7 设置操作hadoop的用户
        System.setProperty("HADOOP_USER_NAME","atguigu");
        */
        //TODO 3.从kafka主题中读取数据
        //3.1 声明消费的主题以及消费者组
        String topic = "topic_db";
        String groupId = "base_db_group";
        //3.2 创建消费者对象
        KafkaSource<String> kafkaSource = KafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据 封装为流
        DataStreamSource<String> kafkaStrDS
            = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafka_source");

        //TODO 4.对流中数据类型进行转换并进行简单的ETL  jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
            new ProcessFunction<String, JSONObject>() {
                @Override
                public void processElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
                    try {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String type = jsonObj.getString("type");
                        if (!type.startsWith("bootstrap-")) {
                            out.collect(jsonObj);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        );
        // jsonObjDS.print(">>>>");

        //TODO 5.使用flinkCDC读取配置表数据
        //5.1 获取mySqlSource
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
            .hostname("hadoop102")
            .port(3306)
            .databaseList("gmall0222_config") // set captured database
            .tableList("gmall0222_config.table_process_dwd") // set captured table
            .username("root")
            .password("123456")
            .startupOptions(StartupOptions.initial())
            .deserializer(new JsonDebeziumDeserializationSchema()) // converts SourceRecord to JSON String
            .build();
        //5.2 封装为流
        DataStreamSource<String> mysqlStrDS
            = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source");
        // mysqlStrDS.print(">>>");

        //TODO 6.对读取到的配置信息进行广播
        MapStateDescriptor<String, BaseDbTableProcess> mapStateDescriptor
            = new MapStateDescriptor<String, BaseDbTableProcess>("mapStateDescriptor",String.class,BaseDbTableProcess.class);
        BroadcastStream<String> broadcastDS = mysqlStrDS.broadcast(mapStateDescriptor);

        //TODO 7.将主流和广播流进行关联
        BroadcastConnectedStream<JSONObject, String> connectDS = jsonObjDS.connect(broadcastDS);

        //TODO 8.对关联之后的数据进行处理
        SingleOutputStreamOperator<JSONObject> realDS = connectDS.process(
            new BaseDbTableProcessFunction(mapStateDescriptor)
        );
        //TODO 9.将需要动态分流处理的事实表数据写到kafka的不同的主题中
        realDS.print(">>>");
        realDS.sinkTo(
            KafkaUtil.getKafkaSinkBySchema(
                new KafkaRecordSerializationSchema<JSONObject>() {
                    @Nullable
                    @Override
                    public ProducerRecord<byte[], byte[]> serialize(JSONObject jsonObj, KafkaSinkContext context, Long timestamp) {
                        String topic = jsonObj.getString("sink_table");
                        jsonObj.remove("sink_table");
                        return new ProducerRecord<byte[], byte[]>(topic,jsonObj.toJSONString().getBytes());
                    }
                }
            )
        );
        env.execute();
    }
}
